'use client';

import { Badge } from '@/components/ui/badge';
import Link from 'next/link';
import { useEffect, useMemo } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { getContentDetail, viewContent } from '@/apis/client/content';
import { getFavoriteStatus, toggleFavorite } from '@/apis/client/favorite';
import { useAuth } from '@/lib/auth-context';
import { useMenu } from '@/contexts/MenuContext';
import { Skeleton } from '@/components/ui/skeleton';
import { toast } from 'sonner';
import { AdSidebar } from '@/components/ad-sidebar';
import { useParams } from 'next/navigation';

export default function NewsDetailPage() {
  const params = useParams();
  const slug = params.slug as string;
  const { user } = useAuth();
  const queryClient = useQueryClient();


  const { data: article, isLoading: isArticleLoading } = useQuery({
    queryKey: ['contentDetail', slug],
    queryFn: () => getContentDetail(slug),
    enabled: !!slug,
  });

  const { data: favoriteStatus, isLoading: isFavoriteStatusLoading } = useQuery({
    queryKey: ['favoriteStatus', article?.id],
    queryFn: () => getFavoriteStatus(article!.id),
    enabled: !!user && !!article,
  });

  useEffect(() => {
    if (article) {
      viewContent(article.id);
    }
  }, [article]);

  const favoriteMutation = useMutation({
    mutationFn: () => toggleFavorite(article!.id),
    onSuccess: () => {
      toast.success(favoriteStatus?.isFavorited ? '已取消收藏' : '收藏成功');
      queryClient.invalidateQueries({
        queryKey: ['favoriteStatus', article?.id],
      });
    },
    onError: () => {
      toast.error('操作失败，请稍后重试');
    },
  });

  const handleFavorite = () => {
    if (!user) {
      toast.error('请先登录再进行收藏');
      return;
    }
    if (!article) return;
    favoriteMutation.mutate();
  };

  if (isArticleLoading) {
    return (
      <div className="container mx-auto px-4 py-8 max-w-[1440px]">
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
          <div className="lg:col-span-2">
            <Skeleton className="h-6 w-1/4 mb-6 bg-gray-200" />
            <Skeleton className="h-8 w-3/4 mb-4 bg-gray-200" />
            <Skeleton className="h-6 w-1/2 mb-8 bg-gray-200" />
            <Skeleton className="w-full h-96 rounded-lg mb-8 bg-gray-200" />
            <Skeleton className="h-4 w-full mb-4 bg-gray-200" />
            <Skeleton className="h-4 w-full mb-4 bg-gray-200" />
            <Skeleton className="h-4 w-5/6 mb-4 bg-gray-200" />
          </div>
          <aside className="lg:col-span-1">
            <AdSidebar />
          </aside>
        </div>
      </div>
    );
  }

  if (!article) {
    return <div>文章不存在</div>;
  }

  return (
    <main className="flex-1 overflow-y-auto">
      <div className="container mx-auto px-4 py-8 max-w-[1440px]">
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
        {/* Main Content */}
        <article className="lg:col-span-2">
          {/* Breadcrumb */}
          <nav className="flex items-center gap-2 text-sm text-muted-foreground mb-6">
            <Link href="/" className="hover:text-primary transition-colors">
              首页
            </Link>
            <span>/</span>
            <Link href="/news" className="hover:text-primary transition-colors">
              热点资讯
            </Link>
            <span>/</span>
            <span className="text-foreground">正文</span>
          </nav>

          {/* Article Header */}
          <div className="mb-6">
    
            <h1 className="text-3xl md:text-4xl font-bold mb-4 text-balance">{article.title}</h1>
            <div className="flex flex-wrap items-center gap-4 text-sm text-muted-foreground">
              <span className="flex items-center gap-1">
                <svg className="h-4 w-4" fill="currentColor" viewBox="0 0 20 20">
                  <path
                    fillRule="evenodd"
                    d="M6 2a1 1 0 00-1 1v1H4a2 2 0 00-2 2v10a2 2 0 002 2h12a2 2 0 002-2V6a2 2 0 00-2-2h-1V3a1 1 0 10-2 0v1H7V3a1 1 0 00-1-1zm0 5a1 1 0 000 2h8a1 1 0 100-2H6z"
                    clipRule="evenodd"
                  />
                </svg>
                {new Date(article.createdAt).toLocaleDateString()}
              </span>
              <span className="flex items-center gap-1">
                <svg className="h-4 w-4" fill="currentColor" viewBox="0 0 20 20">
                  <path d="M10 12a2 2 0 100-4 2 2 0 000 4z" />
                  <path
                    fillRule="evenodd"
                    d="M.458 10C1.732 5.943 5.522 3 10 3s8.268 2.943 9.542 7c-1.274 4.057-5.064 7-9.542 7S1.732 14.057.458 10zM14 10a4 4 0 11-8 0 4 4 0 018 0z"
                    clipRule="evenodd"
                  />
                </svg>
                {article.viewCount} 阅读
              </span>
            </div>
          </div>

          {/* Featured Image */}
          <div className="mb-8 rounded-lg overflow-hidden">
            <img
              src={article.cover?.url || '/icon/default.svg'}
              onError={(e) => { e.currentTarget.src = '/icon/default.svg'; e.currentTarget.onerror = null; }}
              alt={article.title}
              className="w-full h-auto"
            />
          </div>

          {/* Article Content */}
          <div className="prose prose-lg max-w-none mb-8" dangerouslySetInnerHTML={{ __html: article.content }} />

          {/* Favorite Button */}
          <div className="flex justify-center my-8">
            <button
              onClick={handleFavorite}
              disabled={favoriteMutation.isPending || isFavoriteStatusLoading}
              className={`px-6 py-3 rounded-full font-semibold transition-colors flex items-center gap-2 ${
                favoriteStatus?.isFavorited ? 'bg-red-500 text-white' : 'bg-gray-200 text-gray-800'
              }`}>
              {isFavoriteStatusLoading
                ? '加载中...'
                : favoriteStatus?.isFavorited
                ? '已收藏'
                : '收藏'}
            </button>
          </div>

          {/* Tags */}
          <div className="flex flex-wrap gap-2 mb-8 pb-8 border-b border-border">
            <span className="text-sm text-muted-foreground">标签：</span>
            {article.categories.map((category) => (
              <Badge key={category.id} variant="outline">
                {category.name}
              </Badge>
            ))}
          </div>

          {/* Share Buttons */}
          <div className="flex items-center gap-4">
            <span className="text-sm font-medium">分享到：</span>
            <button className="p-2 rounded-md border border-border hover:bg-accent transition-colors">
              <svg className="h-5 w-5" fill="currentColor" viewBox="0 0 24 24">
                <path d="M18 2h-3a5 5 0 00-5 5v3H7v4h3v8h4v-8h3l1-4h-4V7a1 1 0 011-1h3z" />
              </svg>
            </button>
            <button className="p-2 rounded-md border border-border hover:bg-accent transition-colors">
              <svg className="h-5 w-5" fill="currentColor" viewBox="0 0 24 24">
                <path d="M23 3a10.9 10.9 0 01-3.14 1.53 4.48 4.48 0 00-7.86 3v1A10.66 10.66 0 013 4s-4 9 5 13a11.64 11.64 0 01-7 2c9 5 20 0 20-11.5a4.5 4.5 0 00-.08-.83A7.72 7.72 0 0023 3z" />
              </svg>
            </button>
            <button className="p-2 rounded-md border border-border hover:bg-accent transition-colors">
              <svg className="h-5 w-5" fill="currentColor" viewBox="0 0 24 24">
                <circle cx="18" cy="5" r="3" />
                <circle cx="6" cy="12" r="3" />
                <circle cx="18" cy="19" r="3" />
                <line
                  x1="8.59"
                  y1="13.51"
                  x2="15.42"
                  y2="17.49"
                  stroke="currentColor"
                  strokeWidth="2"
                />
                <line
                  x1="15.41"
                  y1="6.51"
                  x2="8.59"
                  y2="10.49"
                  stroke="currentColor"
                  strokeWidth="2"
                />
              </svg>
            </button>
          </div>
        </article>

          {/* Sidebar */}
          <aside className="lg:col-span-1">
            <AdSidebar />
          </aside>
        </div>
      </div>
    </main>
  );
}
